import cache from './cache'
module.exports = {
    isOpen:false,
    start(){
        let that = this;
        wx.connectSocket({
            url: 'wss://play.he29.com/websocket'
        });
        wx.onSocketOpen(function(res){
            that.isOpen = true;
        });
        wx.onSocketError(function(res){
            console.log('WebSocket连接打开失败，请检查！');
            that.isOpen = false;
        });
        wx.onSocketClose(function(res) {
            console.log('WebSocket 已关闭！');
            that.isOpen = false;
        });
    },
    send(name='none',data='',fn,code=1){
        let msgData = {
            action:name,
            data:data,
            code:code,
            uid:cache.get('user_uid'),
            openid:cache.get('user_openid'),
        };
        let SendMsg = JSON.stringify(msgData);
        if (this.isOpen && SendMsg) {
            wx.sendSocketMessage({
                data:SendMsg,
                success:function () {},
                fail:function () {},
                complete:function (res) {
                    fn && fn(res);
                }
            });
        }else{
            setTimeout(()=>{
                this.send(name,data,fn,code)
            },500)
        }
    },
    onSocketMessage(fn){
        wx.onSocketMessage(function(res) {
            let data= JSON.parse(res.data);
            if(data.type != 'ping'){
                fn && fn(data);
            }
        })
    }
};
